package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.Result;
import com.itheima.youdianda.domain.SysConfig;
import com.itheima.youdianda.domain.YddAdvimg;
import com.itheima.youdianda.domain.YddArticle;
import com.itheima.youdianda.domain.YddCate;
import com.itheima.youdianda.domain.YddLink;
import com.itheima.youdianda.domain.YddTag;
import com.itheima.youdianda.domain.YddUser;
import com.itheima.youdianda.dto.qiantaiDto.ArticleDto;
import com.itheima.youdianda.dto.qiantaiDto.ArticlePageDto;
import com.itheima.youdianda.dto.qiantaiDto.ConfigDto.ConfigGroupDto;
import com.itheima.youdianda.dto.qiantaiDto.ConfigDto.GetConfigDto;
import com.itheima.youdianda.dto.qiantaiDto.ConfigDto.ShortConfigDto;
import com.itheima.youdianda.dto.qiantaiDto.IndexDtoz;
import com.itheima.youdianda.dto.qiantaiDto.NewsDto;
import com.itheima.youdianda.dto.qiantaiDto.YddArticlesDto;
import com.itheima.youdianda.service.SysConfigService;
import com.itheima.youdianda.service.YddAdvimgService;
import com.itheima.youdianda.service.YddArticleService;
import com.itheima.youdianda.service.YddCateService;
import com.itheima.youdianda.service.YddLinkService;
import com.itheima.youdianda.service.YddTagService;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/frame/index")
public class QianTaiController {
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddLinkService yddLinkService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private SysConfigService sysConfigService;


    /**
     * 热门置顶文章数据(首页)
     */

    @GetMapping("/new")
    public Result Page(int page, int limit) {
        NewsDto newsDto = new NewsDto();

        //获取系统当前时间
        long nowTime = new Date().getTime();

        //获取一周之前的毫秒值
        long endWeekTime = nowTime - 604800000L;
        //获取24小时之前的毫秒值
        long endDayTime = nowTime - 86400000L;

        //获取24小时最新文章数量
        LambdaQueryWrapper<YddArticle> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.ge(YddArticle::getCreateDate, endDayTime);
        int num_day = (int) yddArticleService.count(queryWrapper1);
        newsDto.setNum_day(num_day);
        //获取一周内最新文章
        LambdaQueryWrapper<YddArticle> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.ge(YddArticle::getCreateDate, endWeekTime);
        int num_week = (int) yddArticleService.count(queryWrapper2);
        newsDto.setNum_week(num_week);

        Page pageInfo = new Page(page, limit);
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(YddArticle::getCreateDate).eq(YddArticle::getStatus, 2);
        yddArticleService.page(pageInfo, queryWrapper);

        ArticlePageDto articlePageDto = new ArticlePageDto();
        BeanUtils.copyProperties(pageInfo, articlePageDto);

        newsDto.setList(articlePageDto);
        newsDto.setDesc("首页大列表");

        return Result.ok(newsDto);
    }

    /**
     * 文章列表数据
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    public Result selectByCateId(int page, int limit, int cateid) {
        LambdaQueryWrapper<YddArticle> qw = new LambdaQueryWrapper<>();
        qw.eq(YddArticle::getCateid, cateid).orderByDesc(YddArticle::getCreateDate);

        Page pageInfo = new Page(page, limit);
        yddArticleService.page(pageInfo, qw);

        ArticlePageDto articlePageDto = yddArticleService.getArticlePageDto(page, limit, qw);


        HashMap<String, Object> ret = new HashMap<>();
        ret.put("list", articlePageDto);
        // TODO: 2022/9/9 属性无法序列化响应到客户端
        return Result.ok(ret);
    }

    /**
     * 用户注册
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public Result register(@RequestBody YddUser yddUser) {
        String username = yddUser.getUsername();
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getUsername, username);
        YddUser yddUserServiceOne = yddUserService.getOne(queryWrapper);
        if (yddUserServiceOne != null) {
            return Result.error("账户已存在");
        }
        String password = yddUser.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        yddUser.setPassword(s);
        yddUser.setUsername("newUser");
        yddUserService.save(yddUser);
        return Result.ok("注册成功");
    }

    /**
     * 最新文章
     *
     * @param
     * @return
     */
    @GetMapping("/hot")
    public Result hot() {
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(YddArticle::getClick)
                .eq(YddArticle::getIshot, 1)
                .last("limit 7");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        List<YddArticlesDto> articlesDtoList = new ArrayList<>(list.size());
        list.stream().forEach(itme -> {
                    YddArticlesDto yddArticlesDto = new YddArticlesDto();
                    BeanUtils.copyProperties(itme, yddArticlesDto);
                    articlesDtoList.add(yddArticlesDto);
                }
        );
        for (YddArticlesDto yddArticlesDto : articlesDtoList) {
            yddArticlesDto.setCatename(yddCateService.getById(yddArticlesDto.getCateid()).getCatename());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("desc", "侧边最新文章");
        map.put("list", articlesDtoList);
        return Result.ok(map);
    }

    /**
     * 推荐文章
     *
     * @return
     */
    @GetMapping("/recommend")
    public Result recommend() {
        HashMap<String, Object> ret = new HashMap<>();

        LambdaQueryWrapper<YddArticle> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(YddArticle::getClick).last("limit 6");

        List<ArticleDto> articleDtos = getArticleDtoList(qw);

        ret.put("desc", "侧边推荐文章");
        ret.put("list", articleDtos);

        return Result.ok(ret);
    }

    //抽取的方法 封装数据
    private List<ArticleDto> getArticleDtoList(LambdaQueryWrapper<YddArticle> qw) {
        return yddArticleService.list(qw).stream().map((item) -> {
            ArticleDto articleDto = new ArticleDto();
            articleDto.setCatename(yddCateService.getById(item.getCateid()).getCatename());
            articleDto.setId(item.getId().toString());
            articleDto.setTitle(item.getTitle());
            articleDto.setPic(item.getPic());
            articleDto.setLovenum(item.getLovenum());
            return articleDto;
        }).collect(Collectors.toList());
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public Result index() {
        IndexDtoz indexDto = new IndexDtoz();
        //AllCate
        indexDto.setAllCate(yddCateService.list());
        //AllLink
        indexDto.setAllLink(yddLinkService.list());
        //AllTag
        indexDto.setAllTag(yddTagService.list());

        //Banner
        LambdaQueryWrapper<YddAdvimg> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(YddAdvimg::getAdvimgpos, "15");
        indexDto.setBanner(yddAdvimgService.list(qw1));

        //SideBanner
        LambdaQueryWrapper<YddAdvimg> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(YddAdvimg::getAdvimgpos, "14");
        indexDto.setSideBanner(yddAdvimgService.list(qw2));

        ////ShowBanner
        //LambdaQueryWrapper<YddAdvimg> qw3 = new LambdaQueryWrapper<>();
        //qw3.lt(YddAdvimg::getAdvimgpos, "14");
        indexDto.setShowBanner(indexDto.getSideBanner());

        //Config
        GetConfigDto getConfigDto = new GetConfigDto();

        List<SysConfig> list = sysConfigService.list();

        //Config_allData
        List<ShortConfigDto> shortConfigDtos = list.stream().map((item) -> {
            ShortConfigDto shortConfigDto = new ShortConfigDto();
            BeanUtils.copyProperties(item, shortConfigDto);
            return shortConfigDto;
        }).collect(Collectors.toList());
        getConfigDto.setAllData(shortConfigDtos);

        //Config_list
        List<ConfigGroupDto> groupDtoList = new ArrayList<>();

        ConfigGroupDto base = new ConfigGroupDto();
        base.setKey("base");
        base.setName("基础配置");
        List<SysConfig> baseList = new ArrayList<>();

        ConfigGroupDto system = new ConfigGroupDto();
        system.setKey("system");
        system.setName("系统设置");
        List<SysConfig> systemList = new ArrayList<>();

        ConfigGroupDto custom = new ConfigGroupDto();
        custom.setKey("custom");
        custom.setName("其他设置");
        List<SysConfig> customList = new ArrayList<>();

        for (SysConfig config : list) {
            String tab = config.getTabValue();
            switch (tab) {
                case "base":
                    baseList.add(config);
                    break;
                case "system":
                    systemList.add(config);
                    break;
                case "custom":
                    customList.add(config);
                    break;
            }
        }
        base.setChildern(baseList);
        system.setChildern(systemList);
        custom.setChildern(customList);

        groupDtoList.add(base);
        groupDtoList.add(system);
        groupDtoList.add(custom);

        getConfigDto.setList(groupDtoList);

        indexDto.setConfig(getConfigDto);

        return Result.ok(indexDto);
    }

    /**
     * 文章详情数据
     *
     * @param id
     * @return
     */
    @GetMapping("/show")
    public Result show(Integer id) {
        //LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq(id != null, YddArticle::getId, id)
        //        .last("limit 4");
        //List<ArticleDto> articleDtoList = getArticleDtoList(queryWrapper);
        YddArticle byId2 = yddArticleService.getById(id);
        // TODO: 2022/9/9 半成品 不会封装了
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid, byId2.getCateid())
                .last("limit 8");
        List<YddArticle> recommend = yddArticleService.list(queryWrapper);

        YddArticle prev = yddArticleService.getById(id - 1);
        List<Map> prevList = new ArrayList<>();
        if(prev != null){
            Map<String, Object> prevMap = new HashMap<>();
            prevMap.put("id", (id - 1));
            prevMap.put("title",prev.getTitle());
            prevList.add(prevMap);
        }
        YddArticle next = yddArticleService.getById(id + 1);
        List<Map> nextList = new ArrayList<>();
        if(next != null){
            Map<String, Object> nextMap = new HashMap<>();
            nextMap.put("id", (id + 1));
            nextMap.put("title", next.getTitle());
            nextList.add(nextMap);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("info", byId2);
        hashMap.put("next", nextList);
        hashMap.put("prev", prevList);
        hashMap.put("recommend", recommend);

        return Result.ok(hashMap);
    }

    /**
     * 前台登录
     *
     * @param yddUser
     * @return
     */
    //@PostMapping("/frame/login")
    //public Result login(@RequestBody YddUser yddUser) {
    //    String username = yddUser.getUsername();
    //    String password = yddUser.getPassword();
    //    String digest = DigestUtils.md5DigestAsHex(password.getBytes());
    //    LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
    //    queryWrapper.eq(YddUser::getPassword, digest)
    //            .eq(YddUser::getUsername, username);
    //    YddUser one = yddUserService.getOne(queryWrapper);
    //    if (one == null) {
    //        return Result.error("密码不正确");
    //    }
    //    HashMap<String, Object> hashMap = new HashMap<>();
    //    hashMap.put("id", one.getId());
    //    String token = JwtUtils.getToken(hashMap);
    //    hashMap = new HashMap<>();
    //    hashMap.put("token", token);
    //    return Result.ok(hashMap);
    //
    //}


}
